package com.runshu.runshuwulian.base.net;

import android.accounts.NetworkErrorException;
import android.content.Context;
import android.text.TextUtils;

import com.runshu.runshuwulian.bean.BaseBean;

import java.net.ConnectException;
import java.net.UnknownHostException;
import java.util.concurrent.TimeoutException;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

public abstract class BaseObserver<T> implements Observer<BaseBean<T>> {
    private static final String TAG = BaseObserver.class.getSimpleName();
    private Context mContext;

    protected BaseObserver() {
    }

    protected BaseObserver(Context context) {
        this.mContext = context;
    }

    @Override
    public void onSubscribe(Disposable d) {

    }

    @Override
    public void onNext(BaseBean<T> tBaseEntity) {
//        if (!TextUtils.isEmpty( tBaseEntity.getCode() )) {
        if ("200".equals( tBaseEntity.getCode() ) || "0".equals( tBaseEntity.getCode() )) {
            try {
                onSuccees( tBaseEntity );
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            try {
                onCodeError( Integer.valueOf( tBaseEntity.getCode() ), tBaseEntity );
//                onCodeError( -1, tBaseEntity );
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onError(Throwable e) {
        try {
            if (e instanceof ConnectException
                    || e instanceof TimeoutException
                    || e instanceof NetworkErrorException
                    || e instanceof UnknownHostException) {
                onFailure( new Throwable( "网络异常，请检查网络" ), true );
            } else {
                onFailure( e, false );
            }
        } catch (Exception e1) {
            e1.printStackTrace();
        }
    }

    /**
     * 返回成功
     *
     * @throws Exception
     */
    protected abstract void onSuccees(BaseBean<T> response) throws Exception;

    /**
     * 返回失败
     *
     * @param e
     * @param isNetWorkError 是否是网络错误
     * @throws Exception
     */
    protected abstract void onFailure(Throwable e, boolean isNetWorkError) throws Exception;

    /**
     * 返回成功了,但是code错误
     *
     * @throws Exception
     */
    protected void onCodeError(int response, BaseBean<T> baseEntity) throws Exception {
        onError( new Throwable( baseEntity.getMessage() ) );
    }

    @Override
    public void onComplete() {

    }
}
